package com.chii.colorization.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.chii.colorization.R;
import com.chii.colorization.ui.fragment.MainActivity.ai.AiFragment;
import com.chii.colorization.utils.JsonUtils;
import com.chii.colorization.utils.connes.MyUrl;
import com.chii.colorization.utils.connes.OkHttpUtil;
import com.chii.colorization.utils.SPUtil;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;

import static com.chii.colorization.utils.ActivityCodes.REQUESTCODE_FROM_LOGIN;
import static com.chii.colorization.utils.ActivityCodes.REQUESTCODE_FROM_USERINFO;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    public static String TAG = MainActivity.class.getName();
    @BindView(R.id.container)
    ConstraintLayout container;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    @BindView(R.id.nav_view)
    NavigationView navigationView;
    TextView signinState;
    ImageView headImage;
    private AppBarConfiguration mAppBarConfiguration;
    private JSONObject token;
    private static Boolean login = false;
    private Snackbar snackbar;
    private Handler mHandler;
    private final List<Integer> FRAGMENT_NAV_ID_LIST = Arrays.asList(
            R.id.nav_ai, R.id.nav_images, R.id.nav_tools,
            R.id.nav_settings, R.id.nav_about
    );
    private final List<Integer> FRAGMENT_TITLE_LIST = Arrays.asList(
            R.string.menu_ai, R.string.menu_images, R.string.menu_tools,
            R.string.menu_settings, R.string.menu_about
    );


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        setSupportActionBar(toolbar);
        initHandler();
        //初始化主题
        initTheme();
        //初始化语言
        changeLanguage();
        //初始化权限
        initPermission();
        //登录部分界面初始化
        initNavigationHeadView(false);
        //初始化侧滑框选择
        initNavigationBodyView();
        //通过网络获取初始化设置
        initConfig();
        //初始化登录状态
        initLogin();
//        debug();
    }

    private void debug() {
        Intent intent = new Intent(this, PayActivity.class);

        startActivity(intent);
    }

    private void initTheme() {
        MenuItem item = navigationView.getMenu().findItem(R.id.nav_daynight);
        if ((Boolean) SPUtil.get(this, "nightTheme", Boolean.FALSE)) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            item.setTitle(R.string.theme_day);
            item.setIcon(R.drawable.ic_wb_sunny_black);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            item.setTitle(R.string.theme_night);
            item.setIcon(R.drawable.ic_brightness_black);
        }
    }

    /**
     * 更新主题切换按钮
     */
    private void upTheme() {
        if ((Boolean) SPUtil.get(this, "nightTheme", Boolean.FALSE)) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            SPUtil.put(MainActivity.this, "nightTheme", Boolean.FALSE);
        } else{
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            SPUtil.put(MainActivity.this, "nightTheme", Boolean.TRUE);
        }
    }

    /**
     * 更换fragment的标签名称
     *
     * @param itemId
     */
    private void updateTitle(int itemId) {
        int titleId = FRAGMENT_TITLE_LIST.get(FRAGMENT_NAV_ID_LIST.indexOf(itemId));
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(titleId);
        }
    }


    private void initPermission() {
        String[] permissions = {Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE};
        //获取权限
        if (!EasyPermissions.hasPermissions(this, permissions)) {
            //没有打开相关权限、申请权限
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
        }
    }

    /*
     * 更改语言
     *
     * */
    private void changeLanguage() {
        Configuration config = this.getResources().getConfiguration();
        if ("US".equals(config.getLocales().toString())) {
            config.setLocale(Locale.ENGLISH);
        } else {
            config.setLocale(Locale.CHINA);
        }
    }

    private void initHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 401:
                        login = false;
//                        initNavigationHeadView(false);
                        break;
                    case 500:
                        Toast.makeText(MainActivity.this, "无法连接服务器！！", Toast.LENGTH_LONG).show();
                        break;
                    default:
                }
                return false;
            }
        });
    }


    private void initConfig() {
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        okHttpUtil.get(MyUrl.config, null, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                System.out.println(s);
                if (!JsonUtils.isJSONValid(s)) {
                    return;
                }
                JSONObject jsonObject = (JSONObject) JSON.parse(s);
                if (jsonObject.containsKey("code")) {
                    int code = jsonObject.getInteger("code");
                    if (code == 200) {
                        SPUtil.put(MainActivity.this, "config", jsonObject.getJSONObject("data").getString("content"));
                        Intent intent = new Intent();
                        intent.setAction("chii.init.config");
                        LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent);
                    }
                }
            }

            @Override
            public void failed(IOException e) {
                Message message = new Message();
                message.what = 500;
                mHandler.sendMessage(message);
            }
        });

    }

    private void initLogin() {
        token = JSONObject.parseObject((String) SPUtil.get(MainActivity.this, "token", ""));
        if (token != null) {
            Long time = token.getLong("end_time");
            //已经token超时
            if (System.currentTimeMillis() > time) {
                //使用refreshToken重新获取token
                refreshToken();
            } else {
                login = true;
//                initNavigationHeadView(true);
            }
        } else {
            login = false;
//            initNavigationHeadView(false);
        }
    }

    private void refreshToken() {
        //url访问以及密码加密
        HashMap<String, String> map = new HashMap<>();
        map.put("refresh_token", token.getString("refresh_token"));
        map.put("client_id", "color-client");
        map.put("client_secret", "FZfXZcltBeng");
        map.put("grant_type", "refresh_token");
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        okHttpUtil.post(MyUrl.oauth, map, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                System.out.println(s);
                if (!JsonUtils.isJSONValid(s)) {
                    return;
                }
                JSONObject jsonObject = (JSONObject) JSON.parse(s);
                if (jsonObject.containsKey("access_token")) {
                    Long time = System.currentTimeMillis() + jsonObject.getInteger("expires_in") * 1000;
                    jsonObject.put("end_time", time);
                    SPUtil.put(MainActivity.this, "token", jsonObject.toString());
                }
                //无效刷新码
                if (jsonObject.containsKey("code")&&jsonObject.getString("code").equals("401")) {
                    SPUtil.remove(MainActivity.this, "token");
                    Message message = new Message();
                    message.what = 401;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void failed(IOException e) {
            }
        });
    }

    /**
     * 处说实话侧边框的上面部分
     */
    private void initNavigationHeadView(boolean login) {
//        if (signinState == null) {
//            View headerView = navigationView.getHeaderView(0);
//            signinState = headerView.findViewById(R.id.signinState);
//            headImage = headerView.findViewById(R.id.headImage);
//            headerView.setOnClickListener(v -> {
//                if (signinState.getText().toString().equals("快点快点,登录！")) {
//                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//                    startActivityForResult(intent, REQUESTCODE_FROM_LOGIN);
//                } else {
//
//                    Intent intent = new Intent(MainActivity.this, UserInfoActivity.class);
//                    startActivityForResult(intent, REQUESTCODE_FROM_USERINFO);
//                }
//            });
//
//        }
        if (snackbar == null) {
            snackbar = Snackbar.make(container, "还没登录哦，请先登录！", Snackbar.LENGTH_INDEFINITE).setAction("Action", null);
            snackbar.getView().setOnClickListener(v -> {
                //打开登录界面
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivityForResult(intent, REQUESTCODE_FROM_LOGIN);
            });
        }
//        if (login) {
//            String saveUsername = (String) SPUtil.get(MainActivity.this, "username", "");
//            signinState.setText(saveUsername);
//            headImage.setImageDrawable(getResources().getDrawable((R.drawable.ic_check_black),
//                    null));
//            snackbar.dismiss();
//        } else {
//            signinState.setText("快点快点,登录！");
//            headImage.setImageDrawable(getResources().getDrawable((R.drawable.ic_close_black),
//                    null));
//            snackbar.show();
//        }
    }


    private void initNavigationBodyView() {
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open,
                R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

//        mAppBarConfiguration = new AppBarConfiguration.Builder(
//                R.id.nav_home, R.id.nav_ai, R.id.nav_images,
//                R.id.nav_tools, R.id.nav_daynight, R.id.nav_settings, R.id.nav_about)
//                .setDrawerLayout(drawer)
//                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
//        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        navigationView.setNavigationItemSelectedListener(item -> {
            int itemId = item.getItemId();
            //在fragment内
            if (FRAGMENT_NAV_ID_LIST.contains(itemId)) {
                updateTitle(itemId);
                navController.navigate(itemId);
            } else if (R.id.nav_daynight == itemId) {
                //切换主题
                upTheme();
//            } else if (R.id.nav_order == itemId) {
//                //打开订单
//                Intent intent = new Intent();
//                intent.setClass(MainActivity.this, PayActivity.class);
//                intent.putExtra("data","get");
//                startActivity(intent);
            } else if (R.id.nav_user == itemId) {
                if (!login) {
                    //打开登录界面
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivityForResult(intent, REQUESTCODE_FROM_LOGIN);
                } else {
                    //打开用户信息界面
                    Intent intent = new Intent(MainActivity.this, UserInfoActivity.class);
                    startActivityForResult(intent, REQUESTCODE_FROM_USERINFO);
                }
            }

            drawer.closeDrawer(GravityCompat.START);
            return true;
        });
    }


    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 当otherActivity中返回数据的时候，会响应此方法
        // requestCode和resultCode必须与请求startActivityForResult()和返回setResult()的时候传入的值一致。
        Log.d(TAG, "onActivityResult: " + requestCode + "  " + resultCode);
        Log.d(TAG, "RESULT_OK " + Activity.RESULT_OK);
        switch (requestCode) {
            case REQUESTCODE_FROM_LOGIN:
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "MainActivity.RESULT_CODE ");
                    login = true;
//                    initNavigationHeadView(true);
                }
                break;
            case REQUESTCODE_FROM_USERINFO:
                if (resultCode == Activity.RESULT_OK) {
                    Toast.makeText(this, "退出成功", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "UserInfoActivity.RESULT_CODE ");
                    login = false;
//                    initNavigationHeadView(false);
                }
                break;
            default:
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //框架要求必须这么写
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //成功打开权限
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
//        Toast.makeText(this, "相关权限获取成功", Toast.LENGTH_SHORT).show();
    }

    //用户未同意权限
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Toast.makeText(this, "请同意相关权限，否则功能无法使用", Toast.LENGTH_SHORT).show();
    }

}
